package ocg.common.re.file;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by chenbo on 2018/3/21.
 */
public class FileOperation {

    static Logger logger = LogManager.getLogger ( FileOperation.class );


    public static String systemPath(){
        String path = System.getProperty ( "user.dir" );
        return path;
    }

    /**
     * 读取url 保存图片
     * @param picUrl
     */
    public static void picWrite( String rootPath , String picUrl) {

        URL url;
        try {
            url = new URL ( picUrl );

            String pi[] = picUrl.split ( "/" );

            String path = rootPath;

            for ( int i = 2; i < pi.length -2 ; i++) {

                if ( !pi[i].equals ( "" )) {
                    if ( path.endsWith ( File.separator )) {
                        path = path + pi[i];
                    } else {
                        path = path + "/" + pi[i];
                    }
                    mkdirs ( path );
                }

            }

           if ( !path.endsWith ( File.separator ) ){
                path = path + File.separator;
           }

           path = path + pi[pi.length-1];

            // 打开URL连接
            URLConnection con = url.openConnection ();
            con.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36");
            // 得到URL的输入流
            InputStream input = con.getInputStream ();
            // 设置数据缓冲
            byte[] bs = new byte[1024 * 2];
            // 读取到的数据长度
            int len;

            // 输出的文件流保存图片至本地
            OutputStream os = new FileOutputStream ( path );
            while ((len = input.read ( bs )) != -1) {
                os.write ( bs, 0, len );
            }
            os.close ();

            input.close ();
        } catch (MalformedURLException e) {
            e.printStackTrace ();
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }

    /**
     * 读取url 保存图片
     * @param picUrl
     */
    public static boolean webPic( String path, String picUrl) {

        URL url;
        try {
            url = new URL ( picUrl );
            // 打开URL连接
            URLConnection con = url.openConnection ();

            con.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36");
            //设置请求超时为5s
            con.setConnectTimeout(5*1000);
            // 得到URL的输入流
            InputStream input = con.getInputStream ();
            // 设置数据缓冲
            byte[] bs = new byte[1024 * 2];
            // 读取到的数据长度
            int len;

            // 输出的文件流保存图片至本地
            OutputStream os = new FileOutputStream ( path );
            while ((len = input.read ( bs )) != -1) {
                os.write ( bs, 0, len );
            }
            os.close ();
            input.close ();
            return true;
        } catch (MalformedURLException e) {
            e.printStackTrace ();
        } catch (IOException e) {
            e.printStackTrace ();
        }
        return false;
    }

    /**
     * 创建文件夹
     * @param path
     * @return
     */
    public static boolean mkdirs( String path ){

        File file = new File ( path );

        if ( file.exists ()){
            return true;
        }
        if ( !path.endsWith ( File.separator ) ){
            path = path + File.separator;
        }
        if (file.mkdir ()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 对string写入到文件
     * @param path
     * @param text
     */
    public static void stringWrite( String path , String text){
        Writer writer = null;

        try {

            writer = new OutputStreamWriter (new FileOutputStream( new File ( path ) ) , "utf-8" );

            writer.write ( text );

            writer.close ();
            logger.debug( "文件写入成功： " + path );
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace ();
        } catch (FileNotFoundException e) {
            e.printStackTrace ();
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }

    public static String stringRead(File path ){

        if ( path.exists() ) {
            InputStream inputStream = null;
            StringBuffer stringBuffer = new StringBuffer (  );
            try {
                inputStream = new FileInputStream( path );

                byte[] bytes = new byte[1024];

                try {
                    for(int n ; ( n = inputStream.read( bytes ) )!=-1 ; ){
                        stringBuffer.append( new String( bytes,0,n,"UTF-8" ) );
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            return stringBuffer.toString();
        }
        return null;
    }
}
